<?php
/* 
 * This class provides key-based cache functionality
 * for this application and since version two it uses
 * memcached-based caching (did disk-based before).
 * 
 * If you have problems with this, ensure you have
 * memcached running, configured properly and the following
 * PHP5 PECL module is required to be installed:
 * 			-- php5-pecl-memcache
 * 
 * 
 * */
class cache{
	// path where the cache files are in
	private $cache_server = CONFIG_CACHE_SERVER;
	private $cache_port = CONFIG_CACHE_PORT;
	private $memcached;
	
	/* constructor that connects to the memcached
	 * server here or throws an error when it does
	 * not exist */
	public function __construct(){
		$this->memcached = new Memcache();
		$this->memcached->connect
			($this->cache_server, $this->cache_port);
	}
	
	/* destructor disconnects memcached */
	public function __destruct(){
		$this->memcached->close();
	}
	
	/* creates a hash value for a message */
	public function hash($message){
		return hash("sha512",$message);
	}
	
	/* returns bool when a certain key exists */
	public function has($key){
		$result = false;
		
		/* check if the key exists in memcached */
		if($this->memcached->get($key)!==false){
			// set the result to true
			$result = true;
		}
		
		return $result;
	}
	
	/* puts data into the cache */
	public function put($key, $value, $expiry){
		// generate the cache key
		$this->memcached->set($key, $value, 0, $expiry);
	}
	
	/* returns data from the cache */
	public function get($key){
		$result = "";
		$cached = $this->memcached->get($key);
		if($cached!==false){
			$result = $cached;
		}
		return $result;
	}
}
?>